package com.wsmlby.vmd.visualization;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class LammpsReader extends VMDDataReader {

	public LammpsReader(File f) throws FileNotFoundException {
		super(f);
	}

	@Override
	public boolean isType() {
		return true;
	}
	private String getLine() throws IOException
	{
		String l;
		do {
			l = mBufferedReader.readLine();
		} while (l.trim().equals("") || l.startsWith("#"));
		return l;
	}
	private boolean checkItem(String CheckTerm) throws IOException {
		String l;
		do {
			l = mBufferedReader.readLine();
			if(l==null)return false;
		} while (l.trim().equals("") || l.startsWith("#"));
		if(!l.startsWith("ITEM: "))
			return false;
		if(!l.substring(6).startsWith(CheckTerm))
			return false;
		return true;
	}
	
	@Override
	public TimeStep getNextTimeStep() throws IOException {
		String l;
		TimeStep t = new TimeStep();
		double [][]bound=new double[2][3];
		if(!checkItem("TIMESTEP"))return null;
		
		l=getLine();
		t.TimeStep=Integer.parseInt(l);
		if(!checkItem("NUMBER OF ATOMS"))return null;
		l=getLine();
		t.NumberOfAtoms=Integer.parseInt(l);
		if(!checkItem("BOX BOUNDS"))return null;
		for(int i=0;i<3;i++)
		{
			l=getLine();
			String []ss=l.split(" ");
			bound[0][i]=Double.parseDouble(ss[0]);
			bound[1][i]=Double.parseDouble(ss[1]);
		}
		
		
		if(!checkItem("ATOMS"))return null;
		for(int i=0;i<t.NumberOfAtoms;i++)
		{
			AtomData a=new AtomData();
			l=getLine();
			String []ss=l.split(" ");
			a.id=ss[0];
			a.Type=Integer.parseInt(ss[1]);
			float []pos=new float[3];
			for(int j=0;j<3;j++)
			{
				pos[j]=(float) (bound[0][j]+Float.parseFloat(ss[j+2])*(bound[1][j]-bound[0][j]));
			}
			a.Position=new Vector3(pos[0],pos[1],pos[2]);
			t.Atoms.add(a);
		}
		return t;
	}

}
